<template>
  <div class="pdf-view">
    <div id="pdf-loading" v-if="loadingTask">
      <div>文档正在加载中……请稍后</div>
      <icon-loading/>
      <div class="logo">
        <img src="logo.svg" width="90" draggable="false" />
      </div>
    </div>
    <div class="control">
      <span style="font-size: 14px;margin-right: 40px;" class="hidden-xs-only">
        <span style="font-size: 12px;vertical-align: text-bottom">
          <file-type-icon :file-name="fileName"/></span>
        <ellipsis :text="fileName" :length="25"></ellipsis>
      </span>
      <span style="font-size: 12px;margin-right: 10px;" class="hidden-sm-and-up">
        <span style="font-size: 12px;vertical-align: text-bottom">
          <file-type-icon :file-name="fileName"/></span>
        <ellipsis :text="fileName" :length="10"></ellipsis>
      </span>
      <a-slider class="hidden-xs-only" style="margin-right: 20px" v-model="currentScale" @change="currentScaleChange" :min="0.5" :max="2"
                :step="0.1" :style="{ width: '200px' }"/>
      <a-button-group style="float: right">
        <a-button size="small" @click="fitScreen">
          <icon-fullscreen v-if="currentScale !== fitWidth"/>
          <icon-shrink v-if="currentScale === fitWidth"/>
        </a-button>
        <a-button size="small" @click="download">
          <icon-download/>
        </a-button>
        <a-button size="small" @click="print">
          <icon-printer/>
        </a-button>
        <a-button size="small" @click="scaleUp()" class="hidden-xs-only">
          <icon-plus/>
          放大
        </a-button>
        <a-button size="small" @click="scaleDown()" class="hidden-xs-only">
          <icon-minus/>
          缩小
        </a-button>
        <a-button v-if="store.fileType !== 'xls' && store.fileType !== 'xlsx'" size="small" status="danger"
                  @click="onQuit">
          <icon-close/>
          退出
        </a-button>

        <a-button v-if="store.fileType === 'xls' || store.fileType === 'xlsx'" size="small" @click="onQuit">
          <template #icon>
            <div style="font-size: 7px; padding-left: 8px; margin-top: -5px">
              <file-type-icon :file-name="'*.xlsx'"></file-type-icon>
            </div>
          </template>
        </a-button>
      </a-button-group>
    </div>
    <div class="animate__animated animate__backInLeft" id="viewerContainer" :class="'pdf-container'" ref="container">
      <div id="viewer" class="pdfViewer"></div>
      <a-divider style="color: #aaa" class="mt-lg"><icon-quote class="mr-md" />到底啦~</a-divider>
    </div>
  </div>
</template>

<script>

import getPdfjsDist from './getPdfjsDist'
import FileTypeIcon from "../fileTypeIcon.vue";
import ElEllipsis from "../ellipsis.vue";
import Print from 'print-js'
import useGlobalStore from "../../store";
import {ref} from "vue";
import router from "../../router";

export default {
  name: 'Pdf',
  components: {ElEllipsis, FileTypeIcon},
  emits: ['onPdfClose'],
  props: {
    url: {
      type: String,
      default: ''
    },
    type: {
      type: String,
      default: 'canvas'
    },
    pdfjsDistPath: {
      type: String,
      default: '.'
    },
    fileName: String
  },
  data() {
    return {
      pdfViewer: null,
      pdfLinkService: null,
      loadingTask: null,
      currentScale: 1,
      source: null,
      fitWidth: 0
    }
  },
  setup() {
    const store = useGlobalStore();
    return {
      store
    }
  },
  methods: {
    onQuit(e) {
      this.$emit("onPdfClose", e);
    },
    scaleUp() {
      if (this.currentScale === 'page-width') {
        this.currentScale = 1;
      }
      this.currentScale += 0.1;
      this.source.currentScaleValue = this.currentScale;
    },
    scaleDown() {
      if (this.currentScale === 'page-width') {
        this.currentScale = 1;
      }
      this.currentScale -= 0.1;
      this.source.currentScaleValue = this.currentScale;
    },
    currentScaleChange(value) {
      this.currentScale = value;
      this.source.currentScaleValue = this.currentScale;
    },
    fitScreen() {
      if (this.currentScale !== this.fitWidth) {
        const tableWidth = document.querySelector("#viewerContainer").scrollWidth + 120;
        const innerWidth = window.innerWidth;
        this.currentScale = Math.min(Math.max(innerWidth / tableWidth, 0.5), 2);
        this.source.currentScaleValue = this.currentScale;
        this.fitWidth = this.currentScale;
      } else {
        this.currentScale = 1;
        this.source.currentScaleValue = this.currentScale;
      }
    },
    download() {
      window.open(this.url);
    },
    onPagesInit({source}) {
      this.source = source;
      source.currentScaleValue = this.currentScale;
    },
    async pdfLibInit() {
      let pdfjsLib = window.pdfjsLib;
      let pdfjsViewer = window.pdfjsViewer
      if (!pdfjsLib || !pdfjsViewer) {
        try {
          await getPdfjsDist(this.pdfjsDistPath)
          this.CMAP_URL = `${this.pdfjsDistPath}/pdf/cmaps/`;
          pdfjsLib = window.pdfjsLib;
          pdfjsLib.GlobalWorkerOptions.workerSrc = `${this.pdfjsDistPath}/pdf/build/pdf.worker.js`
          pdfjsViewer = window.pdfjsViewer
        } catch (error) {
          // console.log(error)
          // pdfjs文件获取失败
          return
        }
      }

      const container = this.$refs.container
      const eventBus = new pdfjsViewer.EventBus();

      // (Optionally) enable hyperlinks within PDF files.
      const pdfLinkService = new pdfjsViewer.PDFLinkService({
        eventBus: eventBus,
      });
      this.pdfLinkService = pdfLinkService
      const pdfViewer = new pdfjsViewer.PDFViewer({
        container: container,
        eventBus: eventBus,
        linkService: pdfLinkService,
        renderer: this.type,
        textLayerMode: 1,
        downloadManager: new pdfjsViewer.DownloadManager({}),
        enableWebGL: true
      });
      this.pdfViewer = pdfViewer;
      pdfLinkService.setViewer(pdfViewer);

      eventBus.on("pagesinit", this.onPagesInit);
      setTimeout(() => {
        this.fitScreen();
        this.loading = false;
      }, 500);
    },
    renderPdf() {
      if (!this.url) {
        return
      }
      // Loading document.
      if (this.pdfViewer === null || this.pdfLinkService === null) {
        return
      }
      if (this.loadingTask !== null) {
        this.loadingTask.destroy()
        this.loadingTask = null
      }
      this.loadingTask = window.pdfjsLib.getDocument({
        cMapUrl: this.CMAP_URL,
        cMapPacked: true,
        url: this.url,
        withCredentials: true
      });
      return this.loadingTask.promise.then((pdfDocument) => {
        if (pdfDocument.loadingTask.destroyed || !this.url) {
          return
        }
        this.pdfViewer.setDocument(pdfDocument)
        this.pdfLinkService.setDocument(pdfDocument, null);
        this.loadingTask = null;
      }).catch(error => {
        console.log(error)
      });
    },
    print() {
      Print({
        printable: this.url,
        type: "pdf",
        showModal: true,
      });
    }
  },
  mounted() {
    window.title = this.fileName;
    this.pdfLibInit().then(() => {
      this.renderPdf();
    })
  },
  watch: {
    url() {
      // 如果存在pdfViewer则取消渲染
      if (this.pdfViewer) {
        this.pdfViewer._cancelRendering()
      }
      this.renderPdf()
    }
  }
}

</script>
<style lang="less">

.pdf-view {
}

.control {
  position: fixed;
  top: 5px;
  right: 5px;
  z-index: 999;
  background: var(--color-bg-1);
  padding: 5px 10px;
  border-radius: 4px;
}

.pdf-container {
  width: 100vw;
  margin-bottom: 60px;
}

#pdf-loading {
  position: absolute;
  width: 200px;
  height: 150px;
  line-height: 50px;
  color: var(--color-text-1);
  font-size: 12px;
  font-weight: 600;
  margin: auto;
  text-align: center;
  left: 0;
  right: 0;
  top: 0;
  bottom: 0;
}
</style>
